package com.itlong.cloud.controller.project;

import com.itlong.cloud.POJO.DTO.operate.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeveloperAuthDeviceAuthVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeveloperAuthVO;
import com.itlong.cloud.POJO.VO.operate.OperateRobotDeveloperDeviceAuthVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.operate.IOperateDeveloperAuthServiceClient;
import com.itlong.cloud.user.operate.IOperatePropertyAccountServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <desc>
 *      运营-开发者授权管理控制器
 * </desc>
 *
 * @createDate 2018/12/18
 */
@RestController
@RequestMapping("/project/developerAuthManage")
public class OperateDeveloperAuthController extends BaseController {

    private final static Logger LOG = LoggerFactory.getLogger(OperateDeveloperAuthController.class);

    @Autowired
    private IOperateDeveloperAuthServiceClient iOperateDeveloperAuthServiceClient;

    @Autowired
    IOperatePropertyAccountServiceClient iOperatePropertyAccountServiceClient;

    /**
     * <desc>
     *      获取开发者授权信息分页列表
     * </desc>
     *
     * @param dto 查询参数DTO
     * @return
     * @author Qiang.S
     * @createDate 2018/12/19
     */
    @RequestMapping(path = "getDeveloperAuthByPage",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object getDeveloperAuthByPage(OperateLoggerDeveloperAuthGetPageDTO dto){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateLoggerDeveloperAuthGetPageDTO.class,request);
            Page<OperateDeveloperAuthVO> page=iOperateDeveloperAuthServiceClient.getDeveloperAuthByPage(dto);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);

        } catch (Exception e) {
            throw new DataAccessException("【运营_项目管理_开发者授权信息getPage】获取分页列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      更新单个物业账号
     * <desc/>
     *
     * @param updateDTO 账号更新信息
     * @return
     * @author Qiang.S
     * @createDate 2018-12-19
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PROPERTY_ACCOUNT_UPDATE_LOG_DESC)
    @RequestMapping(value = "/setStatus", method = RequestMethod.POST)
    @ResponseBody
    public Object setStatus(OperatePropertyAccountUpdateDTO updateDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            updateDTO= HttpProtocolUtil.parseRequestParamToDTO(OperatePropertyAccountUpdateDTO.class,request);
            if (null == updateDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //用户id
            if (StringUtils.isBlank(updateDTO.getUserId())){
                return new MessageVO(OperateErrorCodeEnum.USER_ID_EMPTY_ERR.getErrorCode());
            }
            //状态值 1.正常 2.禁用
            if (null != updateDTO.getStatus() && (updateDTO.getStatus() != DataStatusEnum.NORMAL.getType()
                    && updateDTO.getStatus() != DataStatusEnum.BAN.getType())){
                return new MessageVO(OperateErrorCodeEnum.PROPERTY_ACCOUNT_STATUS_INVALID_ERR.getErrorCode());
            }
            //备注
            if (null != updateDTO.getDescription() && updateDTO.getDescription().length() > 50){
                return new MessageVO(OperateErrorCodeEnum.PROPERTY_ACCOUNT_DESCRIPTION_TOO_LONG_ERR.getErrorCode());
            }
            Integer res = iOperatePropertyAccountServiceClient.updatePropertyAccount(updateDTO);
            return new MessageVO(updateDTO.getUserId(),BaseErrorCodeEnum.SUCCESS.getErrorCode(), res);
        }catch (Exception e){
            throw new DataAccessException("【运营_物业账号管理_物业账号updatePropertyAccount】更新物业账号失败", e);
        }
    }

    /**
     * <desc>
     *      安全设置
     * </desc>
     *
     * @param operateDeveloperAuthSafeSettingsDTO 安全设置DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/12/18
     */
    @ResponseBody
    @PostMapping("safeSettings")
    @LoggerInfo(operateDesc = LogDescConstant.DEVELOPER_AUTH_SAFE_SETTINGS)
    @AuthAccessRequired
    public Object safeSettings(OperateDeveloperAuthSafeSettingsDTO operateDeveloperAuthSafeSettingsDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateDeveloperAuthSafeSettingsDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateDeveloperAuthSafeSettingsDTO.class,request);
            if (operateDeveloperAuthSafeSettingsDTO == null || StringUtils.isBlank(operateDeveloperAuthSafeSettingsDTO.getUserId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (operateDeveloperAuthSafeSettingsDTO.getType() == null || (operateDeveloperAuthSafeSettingsDTO.getType() != 0 && operateDeveloperAuthSafeSettingsDTO.getType() != 1)) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            iOperateDeveloperAuthServiceClient.safeSettings(operateDeveloperAuthSafeSettingsDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营-开发者授权管理】安全设置失败",e);
        }
    }

    /**
     * <desc>
     *      有效期延期设置
     * </desc>
     *
     * @param operateDeveloperAuthMoreValidityDTO 有效期延期设置DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/12/18
     */
    @ResponseBody
    @PostMapping("moreValidity")
    @LoggerInfo(operateDesc = LogDescConstant.DEVELOPER_AUTH_MORE_VALIDITY)
    @AuthAccessRequired
    public Object moreValidity(OperateDeveloperAuthMoreValidityDTO operateDeveloperAuthMoreValidityDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateDeveloperAuthMoreValidityDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateDeveloperAuthMoreValidityDTO.class,request);
            if (operateDeveloperAuthMoreValidityDTO == null || StringUtils.isBlank(operateDeveloperAuthMoreValidityDTO.getUserId())
                    || StringUtils.isBlank(operateDeveloperAuthMoreValidityDTO.getProjectId())
                    || StringUtils.isBlank(operateDeveloperAuthMoreValidityDTO.getAuthValidityPeriodSetType()+"")
                    ) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if ("0".equals(operateDeveloperAuthMoreValidityDTO.getAuthValidityPeriodSetType()+"")){
                if (StringUtils.isBlank(operateDeveloperAuthMoreValidityDTO.getEndTime())||StringUtils.isBlank(operateDeveloperAuthMoreValidityDTO.getStartTime())){
                    return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date endTime = sdf.parse(operateDeveloperAuthMoreValidityDTO.getEndTime());
                    Date nowTime = sdf.parse(sdf.format(new Date()));
                    if (endTime.compareTo(nowTime) < 0) {
                        return new MessageVO(OperateErrorCodeEnum.TIME_AVAILABLE_ERR.getErrorCode());
                    }
                } catch (ParseException e) {
                    return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
                }
            }
            iOperateDeveloperAuthServiceClient.moreValidity(operateDeveloperAuthMoreValidityDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营-开发者授权管理】有效期延期设置失败",e);
        }
    }

    /**
     * <desc>
     *      获取设备授权列表
     * </desc>
     *
     * @param operateDeveloperAuthDeviceAuthListDTO 设备授权列表DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/12/18
     */
    @ResponseBody
    @PostMapping("deviceAuthList")
    public Object deviceAuthList(OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateDeveloperAuthDeviceAuthListDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateDeveloperAuthDeviceAuthListDTO.class,request);
            if (operateDeveloperAuthDeviceAuthListDTO == null || StringUtils.isBlank(operateDeveloperAuthDeviceAuthListDTO.getUserId())
                    || StringUtils.isBlank(operateDeveloperAuthDeviceAuthListDTO.getProjectId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),operateDeveloperAuthDeviceAuthVO);
        } catch (Exception e) {
            throw new DataAccessException("【运营-开发者授权管理】获取设备授权列表失败",e);
        }
    }

    /**
     * <desc>
     *      机器人开发者获取设备授权列表
     * </desc>
     *
     * @param operateDeveloperAuthDeviceAuthListDTO 设备授权列表DTO
     * @return 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2020/03/20
     */
    @ResponseBody
    @PostMapping("robotDeviceAuthList")
    public Object robotDeviceAuthList(OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateDeveloperAuthDeviceAuthListDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateDeveloperAuthDeviceAuthListDTO.class,request);
            if (operateDeveloperAuthDeviceAuthListDTO == null || StringUtils.isBlank(operateDeveloperAuthDeviceAuthListDTO.getUserId())
                    || StringUtils.isBlank(operateDeveloperAuthDeviceAuthListDTO.getProjectId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            OperateRobotDeveloperDeviceAuthVO operateRobotDeveloperDeviceAuthVO = iOperateDeveloperAuthServiceClient.robotDeviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),operateRobotDeveloperDeviceAuthVO);
        } catch (Exception e) {
            throw new DataAccessException("【运营-开发者授权管理】机器人开发者获取设备授权列表失败",e);
        }
    }

    /**
     * <desc>
     *      设备授权
     * </desc>
     *
     * @param operateDeveloperAuthDeviceAuthDTO 设备授权DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/12/18
     */
    @ResponseBody
    @PostMapping("deviceAuth")
    @LoggerInfo(operateDesc = LogDescConstant.DEVELOPER_AUTH_DEVICE_AUTH)
    @AuthAccessRequired
    public Object deviceAuth(OperateDeveloperAuthDeviceAuthDTO operateDeveloperAuthDeviceAuthDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateDeveloperAuthDeviceAuthDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateDeveloperAuthDeviceAuthDTO.class,request);
            if (operateDeveloperAuthDeviceAuthDTO == null || StringUtils.isBlank(operateDeveloperAuthDeviceAuthDTO.getUserId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (operateDeveloperAuthDeviceAuthDTO.getRobotId() == null) {
                operateDeveloperAuthDeviceAuthDTO.setRobotId("");
            }
            if (!"6".equals(operateDeveloperAuthDeviceAuthDTO.getRoleId())
                    && (!NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getCloudIntercomSdk(), 0, 2)
                    || !NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getBluetoothSdk(), 0, 1)
                    //|| !NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getQrCodeSdk(), 0, 1)
                    || !NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getCloudElevatorApi(), 0, 2)
                    || !NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getCloudEntranceApi(), 0, 1)
                    || !NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getVisitorMachineApi(), 0, 1)
                    || !NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getFaceRecognitionApi(), 0, 1)
                    || !NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getOfflineQRCodeSdk(), 0, 1)
                    || !NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getWechatSmallQRCode(), 0, 1)
                    || !NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getWechatSmallBluetoothDocking(), 0, 1)
                    || !NumberHandlerUtil.isInRange(operateDeveloperAuthDeviceAuthDTO.getOnlineQRCodeApi(), 0, 1)
                 )) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
//            if ("6".equals(operateDeveloperAuthDeviceAuthDTO.getRoleId()) && StringUtils.isBlank(operateDeveloperAuthDeviceAuthDTO.getFunctionAuth())) {
//                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
//            }
            iOperateDeveloperAuthServiceClient.deviceAuth(operateDeveloperAuthDeviceAuthDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营-开发者授权管理】设备授权失败",e);
        }
    }

    /**
     * <desc>
     *      接口授权
     * </desc>
     *
     * @param operateDeveloperRobotAuthDeviceAuthDTO 设备授权DTO
     * @return 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2020/03/19
     */
    @ResponseBody
    @PostMapping("robotDeviceAuth")
    @LoggerInfo(operateDesc = LogDescConstant.DEVELOPER_AUTH_DEVICE_AUTH)
    @AuthAccessRequired
    public Object robotDeviceAuth(OperateDeveloperRobotAuthDeviceAuthDTO operateDeveloperRobotAuthDeviceAuthDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateDeveloperRobotAuthDeviceAuthDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateDeveloperRobotAuthDeviceAuthDTO.class, request);
            if (operateDeveloperRobotAuthDeviceAuthDTO == null || StringUtils.isBlank(operateDeveloperRobotAuthDeviceAuthDTO.getUserId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(operateDeveloperRobotAuthDeviceAuthDTO.getRobotNoninductive(), 0, 1)
                    || !NumberHandlerUtil.isInRange(operateDeveloperRobotAuthDeviceAuthDTO.getRobotEntrance(), 0, 1)
                    || !NumberHandlerUtil.isInRange(operateDeveloperRobotAuthDeviceAuthDTO.getRobotToCloud(), 0, 1)) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            iOperateDeveloperAuthServiceClient.robotDeviceAuth(operateDeveloperRobotAuthDeviceAuthDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营-开发者授权管理】机器人开发者设备授权失败", e);
        }
    }

}
